<?php

/**
 * Name: 消息仓库层
 * User: Silent
 * Date: 2025-10-09
 * Time: 15:22:27
 */

namespace App\Repositories\Message;

use App\Models\Message\Message;
use App\Models\Message\UserMessage;
use Buqiu\Repository\Eloquent\Repository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MessageRepository extends Repository
{
    /**
     * 初始化模型.
     *
     * @return string
     */
    public function model(): string
    {
        return Message::class;
    }

    /**
     *  列表.
     *
     * @param array $inputs
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list(array $inputs)
    {
        $userId = request('user_id');
        $query  = Message::query()
            ->join('user_messages', 'messages.id', '=', 'user_messages.message_id')
            ->where('user_messages.employees_id', $userId)
            ->whereNull('user_messages.deleted_at')
            ->whereNull('messages.deleted_at');

        // 类型过滤
        if (!empty($inputs['type']) && $inputs['type'] !== 'undefined') {
            $query->where('messages.type', $inputs['type']);
        }

        // 已读未读过滤
        if (isset($inputs['is_read']) && $inputs['is_read'] !== '' && $inputs['is_read'] !== 'undefined') {
            $status = (int)$inputs['is_read'];
            if (in_array($status, [0, 1])) {
                $query->where('user_messages.status', $status);
            }
        }

        // 内容搜索
        if (!empty($inputs['content']) && $inputs['content'] !== 'undefined') {
            $query->where('messages.content', 'like', '%' . $inputs['content'] . '%');
        }

        $query->orderBy('user_messages.status', 'asc')  // 按照 status 排序
            ->orderBy('user_messages.id', 'desc')    // 按照 user_messages 的 id 排序
            ->orderBy('messages.id', 'desc');

        // 分页
        $page     = $inputs['page']     ?? 1;
        $pageSize = $inputs['pageSize'] ?? 20;

        return $query->paginate($pageSize, ['*'], 'page', $page);
    }

    /**
     *  详情.
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function detail($id)
    {
        return UserMessage::query()
            ->join('messages', 'user_messages.message_id', '=', 'messages.id')
            ->where('user_messages.employees_id', request('user_id'))
            ->where('user_messages.message_id', $id)
            ->whereNull('user_messages.deleted_at')
            ->whereNull('messages.deleted_at')
            ->select('user_messages.*', 'messages.title', 'messages.content', 'messages.type', 'messages.created_at as message_created_at')
            ->first();
    }

    /**
     *  删除.
     *
     * @param $query
     * @return array
     */
    public function destroy($query)
    {
        try {
            DB::transaction(function () use ($query) {
                $messageQuery = Message::query()->find($query->message_id);
                $messageQuery->delete();
                $query->delete();
            });

            return [
                'success' => true,
                'message' => '删除成功',
            ];
        } catch (\Exception $e) {
            Log::channel('message')->error('删除消息失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '删除失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     *  修改状态
     *
     * @param $query
     * @return array
     */
    public function changeStatus($query)
    {
        try {
            if ($query->status == 1) {
                return ['success' => false, 'message' => '已查看'];
            }
            $query->status = 1;
            if ($query->save()) {
                return ['success' => true, 'message' => '查看成功'];
            }

            return ['success' => false, 'message' => '查看失败'];
        } catch (\Exception $e) {
            Log::channel('message')->error('查看消息失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '查看失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * 批量标记已读
     *
     * @return array
     */
    public function markAllRead(): array
    {
        try {
            $userId = request('user_id');

            // 批量更新未读消息状态为已读
            $updatedCount = UserMessage::query()
                ->where('employees_id', $userId)
                ->where('status', 0)
                ->whereNull('deleted_at')
                ->update(['status' => 1]);

            if ($updatedCount > 0) {
                return [
                    'success' => true,
                    'message' => "成功标记 {$updatedCount} 条消息为已读",
                    'updated_count' => $updatedCount
                ];
            }

            return ['success' => false, 'message' => '没有未读消息需要标记'];
        } catch (\Exception $e) {
            Log::channel('message')->error('批量标记已读失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '批量标记已读失败: ' . $e->getMessage(),
            ];
        }
    }
}
